package com.bydq.patrolsystem.controller;

import com.bydq.patrolsystem.annotation.MyLog;
import com.bydq.patrolsystem.service.PsUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class LoginController {

    @Autowired
    private PsUserService psUserService;



    @GetMapping("/login")
    public String login(Integer flag , Model model){
        if(flag!=null&&flag == -1){
            model.addAttribute("msg","请先登录");
        }

        return "login";
    }

    @MyLog("登录系统")
    @PostMapping("/login")
    public String checkLogin(String username , String password , Model model, HttpSession session){

        //验证成功就返回首页   并在当前session中添加用户信息
        if(psUserService.checkLogin(username,password,model)){
            session.setAttribute("user",psUserService.getUserByCode(username));
            return "redirect:/index";
        }

        return "login";
    }

    @MyLog("注销系统")
    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        session.invalidate();

        return "redirect:/user/login";
    }
}
